package com.sxfq.loansupermarket.app.interceptor;

import java.lang.reflect.Method;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.sxfq.loansupermarket.app.constants.AppConstant;
import com.sxfq.loansupermarket.app.dto.AppResponseResult;
import com.sxfq.loansupermarket.business.core.SsoComponent;
import com.sxfq.loansupermarket.business.dto.login.LoginInfoDto;
import com.sxfq.loansupermarket.common.annotation.LoginIntercept;
import com.sxfq.loansupermarket.common.utils.ControllerUtil;

/**
 * 重复请求拦截器
 *
 * @author maoenqi
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private Logger logger = Logger.getLogger(LoginInterceptor.class);
	@Resource
	private SsoComponent ssoComponent;

	/**
	 * 预处理
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// String requestURI = request.getRequestURI();
		Map<String, String> paramMap = ControllerUtil.getRequestParamMap(request);
		String loginToken = ControllerUtil.getCookieLoginToken(request, response);
		// 每次请求刷新登录失效时间
		LoginInfoDto loginInfo = ssoComponent.getLoginInfo(loginToken);
		// logger.info(requestURI + "登录拦截loginToken:" + loginToken);
		// logger.info(requestURI + "登录拦截session:" + request.getSession());
		// Cookie[] cookies = request.getCookies();
		// if (cookies != null) {
		// for (Cookie cookie : cookies) {
		// logger.info("cookie:" + cookie.getName() + "=" + cookie.getValue());
		// }
		// }
		// Enumeration<String> headers = request.getHeaderNames();
		// while (headers.hasMoreElements()) {
		// String name = headers.nextElement();
		// Enumeration<String> values = request.getHeaders(name);
		// while (values.hasMoreElements()) {
		// logger.info("======header:" + name + "=" + values.nextElement());
		// }
		// }
		if (!isCheckLogin(request, response, handler)) {// 不检查登录
			return true;
		}
		if (loginInfo != null) {// 已登录
			logger.info(loginToken + "已登录phone:" + loginInfo.getPhone() + JSON.toJSONString(loginInfo));
			return true;
		} else {// 未登录
			AppResponseResult result = AppResponseResult.build(AppConstant.Code.NOT_LOGIN, AppConstant.Msg.NOT_LOGIN);
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(JSON.toJSONString(result));
			logger.info("未登录,paramMap=" + paramMap);
			return false;
		}
	}

	/**
	 * 返回处理（异常不执行）
	 */
	@Override
	public void postHandle(HttpServletRequest hsr, HttpServletResponse hsr1, Object o, ModelAndView mav)
			throws Exception {
	}

	/**
	 * 后处理（异常执行）
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception excptn) throws Exception {
	}

	private boolean isCheckLogin(HttpServletRequest request, HttpServletResponse response, Object handler) {
		Method method = null;
		Class<?> clazz = null;
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			clazz = handlerMethod.getBeanType();
			method = handlerMethod.getMethod();
		}
		boolean checkBool = false;
		if (clazz != null) {
			LoginIntercept loginIntercept = clazz.getAnnotation(LoginIntercept.class);
			if (loginIntercept != null) {
				checkBool = loginIntercept.checkLogin();
			}
		}
		if (method != null) {
			LoginIntercept loginIntercept = method.getAnnotation(LoginIntercept.class);
			if (loginIntercept != null) {
				checkBool = loginIntercept.checkLogin();
			}
		}
		return checkBool;
	}
}
